package com.cy.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cy.bean.UserList;
import com.cy.service.AddUserService;
import com.cy.service.AddUserServiceImpl;

/**
 * Servlet implementation class AddUserServlet
 */
@WebServlet("/adduser")
public class AddUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置前端页面传递回来的字符编码
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");

		String action = request.getParameter("action");
		AddUserService addUserService = new AddUserServiceImpl();
		if (action == null) {
			// 跳转到添加页面
			request.setAttribute("mainRight", "/WEB-INF/jsp/adduser.jsp");
			request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request, response);
		} else if (action != null && action.equals("add")) {
			String name = request.getParameter("name");
			int sex = Integer.parseInt(request.getParameter("sex"));
			int age = Integer.parseInt(request.getParameter("age"));
			String username = request.getParameter("username");
			String email = request.getParameter("email");
			boolean flag = addUserService.findUsername(username);
			if (flag) {
				UserList user = new UserList(0, name, sex, age, username, "123456", email, 1);
				flag = addUserService.addUser(user);
				if (flag) {
					request.setAttribute("flag", 1);
				} else {
					request.setAttribute("flag", 2);
				}
			} else {
				request.setAttribute("flag", 3);
			}
			request.setAttribute("mainRight", "/WEB-INF/jsp/adduser.jsp");
			request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request, response);
		}
	}

}
